﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace Common
{
    public class Document
    {
        private Bitmap bitmap;

        List<Bitmap> undoStack = new List<Bitmap>();
        List<Bitmap> redoStack = new List<Bitmap>();
        int maxUndoCount = 0;

        public Bitmap GetBitmap()
        {
            return bitmap;
        }

        public void SetMaxUndoCount(int n)
        {
            maxUndoCount = n;
        }

        public void SetBitmap(Bitmap bit)
        {
            if (maxUndoCount > 0)
            {
                if (undoStack.Count > maxUndoCount)
                {
                    undoStack.First().Dispose();
                    undoStack.RemoveAt(0);
                }
                undoStack.Add(bitmap);
                foreach (var bmp in redoStack)
                    bmp.Dispose();
                redoStack.Clear();
            }
            bitmap = bit;
        }

        public void SetBitmapPreview(Bitmap bit)
        {
            bitmap = bit;
        }

        public bool CanUndo()
        {
            return undoStack.Count > 0;
        }

        public bool CanRedo()
        {
            return redoStack.Count > 0;
        }

        public void Undo()
        {
            if (undoStack.Count > 0)
            {
                redoStack.Add(bitmap);
                bitmap = undoStack.Last();
                undoStack.RemoveAt(undoStack.Count - 1);
            }
        }

        public void Redo()
        {
            if (redoStack.Count > 0)
            {
                undoStack.Add(bitmap);
                bitmap = redoStack.Last();
                redoStack.RemoveAt(redoStack.Count - 1);
            }
        }

        public Document(string fileName)
        {
            Image img = Image.FromFile(fileName);
            bitmap = new Bitmap(img);
        }

        public Document()
        {
            bitmap = new Bitmap(1, 1);
        }

        void Dispose()
        {
            bitmap.Dispose();
            foreach (var bmp in redoStack)
                bmp.Dispose();
            foreach (var bmp in undoStack)
                bmp.Dispose();
        }

        void Save(string fileName)
        {
            bitmap.Save(fileName);
        }
    }
}
